<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="clear">
            <el-button slot="append" icon="el-icon-search" @click="getUserLists"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--    用户列表区-->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="180px">
          <template slot-scope="scope">
            <!--              修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)"></el-button>
            <!--              删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
            <!--              分配角色-->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!--    添加用户对话框-->
      <el-dialog
        title="添加用户"
        :visible.sync="addUserDialogVisible"
        width="50%">
        <el-form ref="addUserFromRef" :rules="addUserFromRules" :model="addUserFrom" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserFrom.password" 调用 type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserClick">确 定</el-button>
      </span>
      </el-dialog>
      <!--修改用户对话框-->
      <el-dialog
        title="修改用户"
        :visible.sync="editUserDialogVisible"
        width="50%">
        <el-form ref="editUserFormRef" :rules="addUserFromRules" :model="editUserForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserClick">修 改</el-button>
      </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
  import {getUserList, changeUserState, addUser, delUser,requestEditUser} from '../../network/home'

  export default {
    name: "Users",
    data() {
      var checkEmail = (rule, value, callback) => {
        var regExp = '^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$';
        if (!new RegExp(regExp).test(value)) {
          return callback(new Error('邮箱格式错误'))
        }
        callback()
      }
      var checkMobile = (rule, value, callback) => {
        var regExp = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/;
        if (!new RegExp(regExp).test(value)) {
          return callback(new Error('手机号格式错误'))
        }
        callback()
      }
      return {
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        userList: [],
        total: 0,
        addUserDialogVisible: false,
        addUserFrom: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        editUserForm: {
          id:'',
          username: '',
          email: '',
          mobile: ''
        },
        addUserFromRules: {
          username: [
            {required: true, message: '请输入名称', trigger: 'blur'},
            {min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'}
          ]
        },
        editUserDialogVisible: false
      }
    },
    methods: {
      getUserLists() {
        getUserList(this.queryInfo).then(res => {
          console.log(res);
          if (res.meta.status !== 200) return this.$message.error('数据获取失败')
          this.userList = res.data.users
          this.total = res.data.total
        })
      },
      handleSizeChange(newSize) {
        console.log(newSize);
        this.queryInfo.pagesize = newSize
        this.getUserLists()
      },
      handleCurrentChange(newCurrent) {
        console.log(newCurrent);
        this.queryInfo.pagenum = newCurrent
        this.getUserLists()
      },
      userStateChange(userInfo) {
        console.log(userInfo);
        changeUserState(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(res => {
          console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('切换失败')
            userInfo.mg_state = !userInfo.mg_state
          }
          this.$message.success("切换成功")
        })
      },
      clear() {
        this.getUserLists()
      },
      addUserClick() {
        this.$refs.addUserFromRef.validate(valid => {
          console.log(this.addUserFrom);
          if (!valid) return this.$message.error("数据校验失败")
          addUser(this.addUserFrom).then(res => {
            console.log(res);
            if (res.meta.status != 201) return this.$message.error('用户添加失败:' + res.meta.msg)
            this.$message.success(res.meta.msg)
            //清空表单数据
            this.$refs.addUserFromRef.resetFields()
            this.addUserDialogVisible = false
          })
        })
      },
      delUser(id) {
        delUser(id).then(res => {
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUserLists()
        })
      },
      editUserClick() {
        this.$refs.editUserFormRef.validate(valid=>{
          console.log(valid);
          if(!valid) return
          requestEditUser(this.editUserForm).then(res=>{
            if (res.meta.status!==200) return this.$message.error('修改用户失败')
            this.$message.success('修改用户成功')
          })
          this.editUserDialogVisible = false
          this.getUserLists()
        })
      },
      editUser(userInfo) {
        this.editUserForm.username = userInfo.username
        this.editUserForm.email = userInfo.email
        this.editUserForm.mobile = userInfo.mobile
        this.editUserForm.id = userInfo.id
        this.editUserDialogVisible = true
      }
    },
    created() {
      this.getUserLists()
    }
  }
</script>

<style lang="less" scoped>

</style>
